package com.bayair.doctor.mvp.proxy;



import com.bayair.doctor.mvp.BasePresenter;
import com.bayair.doctor.mvp.IView;
import com.bayair.doctor.mvp.annotation.InjectPresenter;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class ProxyImpl implements IProxy {

    private IView mView;
    /**
     * 保存使用注解的 presenter ，用于解绑
     */
    private List<BasePresenter> mInjectPresenters;

    public ProxyImpl(IView view) {
        mView = view;
        mInjectPresenters = new ArrayList<>();
    }

    @Override
    public void bindPresenter() {
        //反射获取 已经申明的变量，包括私有的
        Field[] fields = mView.getClass().getDeclaredFields();
        for (Field field : fields) {
            //获取变量上面的注解类型
            InjectPresenter injectPresenter = field.getAnnotation(InjectPresenter.class);
            if (injectPresenter != null) {
                //获取BasePresenter类型的变量 类型
                Class<? extends BasePresenter> type = (Class<? extends BasePresenter>) field.getType();
                try {
                    //反射创建实例 presenter 并关联 view
                    BasePresenter basePresenter = type.newInstance();
                    basePresenter.attachView(mView);

                    //反射检查
                    field.setAccessible(true);
                    //赋值给被注解的变量
                    field.set(mView, basePresenter);

                    mInjectPresenters.add(basePresenter);

                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (ClassCastException e) {
                    e.printStackTrace();
                    throw new RuntimeException("SubClass must extends Class:BasePresenter");
                }
            }
        }

    }

    @Override
    public void unbindPresenter() {
        for (BasePresenter presenter : mInjectPresenters) {
            presenter.detachView();
        }
        mInjectPresenters.clear();
        mInjectPresenters = null;
    }
}
